<template>
  <div class="add-container">
    <purchase-header/>
    <div class="w">
      <div class="add-purchase-form w">
        <el-form ref="form" :model="form" :rules="formRules" label-width="110px">
          <p class="form-title">标题</p>
          <el-form-item label="采购单标题" prop="title">
            <el-input v-model="form.title" size="small" placeholder="为该采购单填写标题（必填项）"
              maxlength="60"></el-input>
          </el-form-item>

          <p class="form-title">采购商品计划</p>
          <el-form-item label="商品计划" prop="goods_names">
            <el-radio-group v-model="form.goods_type">
              <el-radio :label="0">现货/标准品</el-radio>
              <el-radio :label="1">加工/订制品</el-radio>
            </el-radio-group>
            <el-table :data="[{}]" border>
              <el-table-column label="商品名称">
                <el-input v-model="form.goods_names"></el-input>
              </el-table-column>
              <el-table-column label="商品分类">
                <el-select v-model="form.goods_category">
                  <el-option v-for="item in categories" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-table-column>
              <el-table-column label="数量">
                <el-input-number v-model="form.goods_num" size="small" :controls="false"></el-input-number>
              </el-table-column>
              <el-table-column label="单位">
                <el-input v-model="form.goods_unit" placeholder="件/把/个/瓶..." :minlength="4"></el-input>
              </el-table-column>
              <el-table-column label="规格">
                <el-input v-model="form.goods_sku" placeholder="规格说明"></el-input>
              </el-table-column>
              <el-table-column label="图片/图纸">
                <el-upload multiple
                  accept=".jpg,.png" :action="MixinUploadApi" :headers="MixinAccessToken" :on-success="onUploadSuccess" :on-remove="onRemoveImage" :limit="1">
                  <el-button size="small" type="primary">点击上传</el-button>
                </el-upload>
              </el-table-column>
            </el-table>
          </el-form-item>

          <p class="form-title">采购需求</p>
          <el-form-item label="采购截止时间" prop="closing_date">
            <el-date-picker
              v-model="form.closing_date"
              type="date"
              size="small"
              value-format="timestamp"
              :picker-options="{disabledDate(time) { return time.getTime()  <  (Date.now() - 8.64E7)   ||  time.getTime()   > Date.now()  + (8.64E7 * 29) }}"
              placeholder="请选择截止时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="期望收货时间" prop="receiving_date">
            <el-date-picker
              v-model="form.receiving_date"
              type="date"
              size="small"
              value-format="timestamp"
              :picker-options="{disabledDate(time) { return time.getTime()  <  (Date.now() - 8.64E7)   ||  time.getTime()   > Date.now()  + (8.64E7 * 29) }}"
              placeholder="请选择期望收货时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="价格说明" prop="goods_price" class="form-item-group">
            <el-radio-group v-model="form.price_type">
              <el-radio :label="0">可议价</el-radio>
              <el-radio :label="1">不可议价</el-radio>
              <el-radio :label="2">面议</el-radio>
            </el-radio-group>
            <div class="form-item-inline goods-price-item">
              <span class="form-item-title">商品单价</span>
              <el-input v-model="form.goods_price" size="small" placeholder="请填写商品单价"
                onkeyup="this.value=this.value.replace(/[^\d.]/g,'');" maxlength="8">
                <template slot="prepend">￥</template>
              </el-input>
            </div>
          </el-form-item>
          <el-form-item label="收货地" prop="ship_county">
            <en-region-cascader
              :province.sync="form.ship_province"
              :city.sync="form.ship_city"
              :county.sync="form.ship_county"
            />
          </el-form-item>
          <el-form-item label="对供应商要求" prop="seller_county" class="form-item-group">
            <div class="form-item-inline">
              <span class="form-item-title">经营地址</span>
              <en-region-cascader
                :province.sync="form.seller_province"
                :city.sync="form.seller_city"
                :county.sync="form.seller_county"
              />
            </div>
            <div class="form-item-inline">
              <span class="form-item-title">发票要求</span>
              <el-radio-group v-model="form.need_receipt">
                <el-radio :label="0">无需发票</el-radio>
                <el-radio :label="1">需要发票</el-radio>
              </el-radio-group>
            </div>
          </el-form-item>
          <el-form-item label="补充说明" prop="purchase_explain">
            <el-input v-model="form.purchase_explain" type="textarea" :rows="4" resize="none"/>
          </el-form-item>

          <p class="form-title">询价方式及隐私</p>
          <el-form-item label="联系方式" prop="privacy">
            <el-radio-group v-model="form.privacy">
              <el-radio :label="0">报价后可见</el-radio>
              <el-radio :label="1">公开</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="联系人" prop="contact_name" class="input-max-width">
            <el-input v-model="form.contact_name" size="small" placeholder="请填写联系人姓名"></el-input>
          </el-form-item>
          <el-form-item label="联系电话" prop="contact_num" class="input-max-width">
            <el-input v-model="form.contact_num" size="small" placeholder="请填写联系电话"></el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSubmitForm">确认提交</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import * as API_Purchase from '@/api/purchase'
import PurchaseHeader from './-PurchaseHeader'
import Storage from '@/utils/storage'
import { RegExp } from '~/ui-utils'
import {
  Form,
  FormItem,
  Input,
  InputNumber,
  RadioGroup,
  Radio,
  Table,
  TableColumn,
  Select,
  Option,
  Upload,
  DatePicker
} from 'element-ui'

Vue.use(Form)
  .use(FormItem)
  .use(Input)
  .use(InputNumber)
  .use(RadioGroup)
  .use(Radio)
  .use(Table)
  .use(TableColumn)
  .use(Select)
  .use(Option)
  .use(Upload)
  .use(DatePicker)

export default {
  name: 'add-purchase',
  layout: 'full',
  components: { PurchaseHeader },
  data() {
    return {
      layer: null,
      form: {
        // 标题
        title: '',
        // 商品类型，现货/标准品：0，加工/订制品：1
        goods_type: 0,
        // 商品名称
        goods_names: '',
        // 商品分类
        goods_category: '',
        // 商品数量
        goods_num: 1,
        // 商品单位，件、把、个、瓶
        goods_unit: '',
        // 商品sku
        goods_sku: '',
        // 商品图片
        goods_img: '',
        // 截止时间
        closing_date: '',
        // 期望收货时间
        receiving_date: '',
        // 价格类型，可议价：0，不可议价：1 ，面议：2
        price_type: 0,
        // 商品单价
        goods_price: '',
        // 买家收货地址-省
        ship_province: '',
        // 买家收货地址-市
        ship_city: '',
        // 买家收货地址-县区
        ship_county: '',
        // 要求卖家地址-省
        seller_province: '',
        // 要求卖家地址-市
        seller_city: '',
        // 要求卖家地址-县区
        seller_county: '',
        // 是都需要发票，不需要：0，需要：1
        need_receipt: 0,
        // 补充说明
        purchase_explain: '',
        // 联系方式隐私，报价后可见：0，公开：1
        privacy: 0,
        // 联系人姓名
        contact_name: '',
        // 联系人电话
        contact_num: ''
      },
      formRules: {
        title: this.MixinRequired('请填写采购单标题'),
        goods_names: [
          this.MixinRequired('请填写商品名称！'),
          {
            validator: (rule, value, callback) => {
              if (!this.form.goods_category) {
                callback(new Error('请选择商品分类！'))
              } else if (!RegExp.integer.test(this.form.goods_num)) {
                callback(new Error('商品数量填写有误！'))
              } else if (!this.form.goods_unit) {
                callback(new Error('请填写商品单位！'))
              } else {
                callback()
              }
            }
          }
        ],
        closing_date: this.MixinRequired('请选择采购截止时间！'),
        receiving_date: this.MixinRequired('请选择期望收货时间！'),
        goods_price: [
          this.MixinRequired('请填写商品单价！'),
          {
            validator: (rule, value, callback) => {
              if (!RegExp.money.test(value)) {
                callback(new Error('请填写正确的价格！'))
              } else {
                callback()
              }
            }
          }
        ],
        ship_county: this.MixinRequired('请选择收货地址！'),
        seller_county: this.MixinRequired('请选择供应商经营地址！'),
        contact_name: this.MixinRequired('请填写联系人姓名！'),
        contact_num: [
          this.MixinRequired('请填写联系电话！'),
          {
            validator: (rule, value, callback) => {
              if (!RegExp.mobile.test(value)) {
                callback(new Error('手机格式有误！'))
              } else {
                callback()
              }
            }
          }
        ],
        purchase_explain: this.MixinRequired('请填写补充说明！')
      }
    }
  },
  mounted() {
    this.checkLogin()
  },
  computed: {
    // 商品分类
    categories() {
      let { categories } = this.$store.getters
      return categories.map(item => ({
        label: item.name,
        value: item.category_id
      }))
    }
  },
  methods: {
    /**
     * 商品图片上传成功
     * @param response
     * @param file
     */
    onUploadSuccess(response, file) {
      this.form.goods_img = response.url
    },
    /**
     * 移除商品图片
     */
    onRemoveImage() {
      this.form.goods_img = ''
    },
    /**
     * 提交表单
     */
    handleSubmitForm() {
      // if (!this.checkLogin()) return
      const params = JSON.parse(JSON.stringify(this.form))
      params.closing_date /= 1000
      params.receiving_date /= 1000
      this.$refs['form'].validate(async(valid) => {
        if (!valid) {
          this.$message.error('表单填写有误，请核对！')
          return false
        }
        await API_Purchase.addPurchase(params)
        this.$alert('发布成功！')
        this.$router.push({ path: '/purchase' })
      })
    },
    /**
     * 检查登录状态
     */
    checkLogin() {
      if (!Storage.getItem('refresh_token')) {
        this.$alert('您还未登录，请登录后再发布！', () => {
          this.$router.push({ path: '/login', query: { forward: `${this.$route.path}` } })
        })
        return false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../../assets/styles/color';
.add-purchase-form {
  width: 100%;
  height: 100%;
  padding: 15px 30px;
  box-sizing: border-box;
  /*background-color: #F2F2F2;*/
  /deep/ {
    table {
      thead th {
        padding: 0;
        text-align: center;
      }
      .cell {
        text-overflow: initial;
        text-align: center;
      }
      .el-input__inner {
        height: 30px;
        line-height: 30px;
      }
      .el-input-number {
        width: 95px;
      }
      .el-select__caret {
        line-height: 30px;
      }
    }
    .form-title {
      position: relative;
      line-height: 40px;
      font-size: 14px;
      padding-left: 15px;
      border-bottom: 1px dashed #c0c4cc;
      margin-bottom: 10px;
      &::before {
        content: ' ';
        position: absolute;
        left: 0;
        top: 50%;
        margin-top: -9px;
        width: 4px;
        height: 18px;
        background-color: $color-main;
        border-radius: 2px;
      }
    }
    .form-item-group {
      .form-item-title {
        margin-right: 10px;
      }
      .el-form-item__content {
        margin-left: 100px;
        border: 1px dashed #c0c4cc;
        padding: 10px;
        border-radius: 5px;
      }
    }
    .input-max-width {
      .el-input {
        width: 220px;
      }
    }
    .form-item-inline {
      display: flex;
      align-items: center;
    }
    .goods-price-item {
      width: 300px;
      .el-input {
        width: 180px;
      }
    }
  }
}
</style>
